//
//  SKHomeViewController.m
//  Sudoku
//
//  Created by Richard Hodgkins on 08/09/2012.
//  Copyright (c) 2012 Richard Hodgkins. All rights reserved.
//

#import "SKHomeViewController.h"

#import "ExpandableNSFetchedResultsController.h"
#import "SKSudokuViewController.h"

#import "SKViewSectionBoard.h"

#import "SKCoreData.h"

#import "SKBoard+Helper.h"

#define SECTION_HEIGHT 32
#define SECTION_IMAGE_INSET 12

#define CELL_IDENTIFIER_BOARD @"Board.cell_identifier"

#define TAG_SECTION_MASK -1

@interface SKHomeViewController ()

@property (nonatomic, strong) ExpandableNSFetchedResultsController *resultsController;

@end

@implementation SKHomeViewController

- (id)init
{
    self = [super initWithStyle:UITableViewStylePlain];
    if (self) {
        // Custom initialization
        self.title = @"Boards";
        
        // Setup fetch controller
        self.resultsController = [[ExpandableNSFetchedResultsController alloc] initWithFetchRequest:[SKBoard fetchRequest] managedObjectContext:[SKCoreData sharedInstance].managedObjectContext sectionNameKeyPath:COL_SKBOARD_DIFFICULTY cacheName:nil];
        
        self.delegate = self;
        self.tableView.sectionHeaderHeight = SECTION_HEIGHT;
                
        [self expandSection:0];
    }
    return self;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return IS_IPAD() || interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return IS_IPAD() ? UIInterfaceOrientationMaskAll : UIInterfaceOrientationMaskAllButUpsideDown;
}

-(BOOL)shouldAutorotate
{
    return YES;
}

#pragma mark - Fetched results table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self.resultsController isSectionExpanded:section]) {
        return [super tableView:tableView numberOfRowsInSection:section];
    } else {
        return 0;
    }
}

- (UITableViewCell *) tableView:(UITableView *)tableView newCellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_IDENTIFIER_BOARD];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CELL_IDENTIFIER_BOARD];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    return cell;
}

- (void) tableView:(UITableView *)tableView updateCellForRow:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    SKBoard *board = [self.resultsController objectAtIndexPath:indexPath];
    
    cell.textLabel.text = board.name;
    if (board.moves) {
        cell.textLabel.text = [cell.textLabel.text stringByAppendingString:@" *"];
    }
    cell.detailTextLabel.hidden = board.bestScore <= 0;
    cell.detailTextLabel.text = [board bestTimeString];
    
    [cell setNeedsLayout];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    switch (section) {
        case SKBoardDifficultyEasy:
            return @"Easy";
        case SKBoardDifficultyMedium:
            return @"Medium";
        case SKBoardDifficultyHard:
            return @"Hard";
            
        default: // Fail case
            return [[[self.resultsController sections] objectAtIndex:section] name];
    }
}

- (UIView*) tableView: (UITableView*) tableView viewForHeaderInSection: (NSInteger) section
{
    NSString *title = [self tableView:self.tableView titleForHeaderInSection:section];
    
    CGRect frame = CGRectMake(0, 0, self.tableView.bounds.size.width, [self tableView:tableView heightForHeaderInSection:section]);
    
    UIButton *button = [[SKViewSectionBoard alloc] initWithFrame:frame title:title tag:(TAG_SECTION_MASK - section)];

    [button setImageEdgeInsets:UIEdgeInsetsMake(SECTION_IMAGE_INSET, SECTION_IMAGE_INSET / 2.0, SECTION_IMAGE_INSET, frame.size.width - (SECTION_HEIGHT - (SECTION_IMAGE_INSET * 1.5)))];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -SECTION_IMAGE_INSET, 0, 0)];

    [button addTarget:self action:@selector(didSelectSection:) forControlEvents:UIControlEventTouchUpInside];
    
    button.selected = [self.resultsController isSectionExpanded:section];
    
    return button;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{ 
    UIViewController *boardViewController = [[SKSudokuViewController alloc] initWithBoard:[self.resultsController objectAtIndexPath:indexPath]];
    [self.navigationController pushViewController:boardViewController animated:YES];
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void) didSelectSection:(id) sender
{
    const NSUInteger section = TAG_SECTION_MASK - [sender tag];
    [self expandSection:section];
    [sender setSelected:[self.resultsController isSectionExpanded:section]];
}

-(void) expandSection:(NSUInteger) section
{
    const BOOL wasChanged = [self.resultsController toggleSectionExpanded:section];
    if (wasChanged) {
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
    }
}

@end
